package com.lcy.accumulation.export.setting;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>创建时间：2017-5-23 13:47</p>
 *
 * @author 娄存银
 * @version 1.0
 */
public abstract class ExportHelper {
    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;

    protected TableSetting setting;
    protected Map<String, Object> header;
    protected List<Map<String, Object>> body;
    protected boolean init;

    public ExportHelper(TableSetting setting, Map<String, Object> header) {
        this.setting = setting;
        this.header = header;
    }

    public ExportHelper(TableSetting setting, List<Map<String, Object>> body) {
        this.setting = setting;
        this.body = body;
    }

    public ExportHelper(TableSetting setting, Map<String, Object> header, List<Map<String, Object>> body) {
        this.setting = setting;
        this.header = header;
        this.body = body;
    }

    public abstract void export(OutputStream outputStream) throws IOException;

    protected List<ExportColumn> getColumns() {
        if (setting != null && setting.getBody() != null) {
            return setting.getBody().getColumns();
        }
        return null;
    }

    protected List<ExportCell> getHeaderCells() {
        if (setting != null && setting.getHeader() != null) {
            return setting.getHeader().getCells();
        }
        return null;
    }

    protected ExportTemplate getTemplateSetting() {
        return setting == null ? null : setting.getTemplate();
    }

    protected ExportStyle getStyleSetting() {
        return setting == null ? null : setting.getStyle();
    }

    protected ExportBody getBodySetting() {
        return setting == null ? null : setting.getBody();
    }

    protected ColumnHandler getColumnHandler() {
        ExportBody bodySetting = getBodySetting();
        return bodySetting == null ? null : bodySetting.getHandler();
    }

    protected ExportHeader getHeaderSetting() {
        return setting == null ? null : setting.getHeader();
    }

    public void init() {
        if (!isValid() || init) {
            return;
        }

        writeHeader();
        writeBody();
        afterExport();

        init = true;
    }

    protected void afterExport() {
    }

    protected abstract void writeHeader();

    protected abstract void writeBody();

    protected boolean isValid() {
        if (setting == null) {
            return false;
        }

        if (!isValidBody() && header == null) {
            return false;
        }

        return true;
    }

    protected boolean isValidBody() {
        return !(body == null || body.size() == 0);
    }
}
